// pages/member/index.js
const util = require('../../utils/util.js');
const apiUrl = require('../../utils/apiUrl.js');
var http = require('../../utils/httpHelper.js');
var dateTimePicker = require('../../utils/dateTimePicker.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    inputViewShow: false,
    navSelectIndex: 0,
    keyword: "",
    editID: 0,
    adminID: 0,
    adminName: '',
    dataList: [],
    orgArray: [],
    orgNameArray: [],
    orgID: 0,
    orgIndex: 0,
    levelArray: [],
    levelNameArray: [],
    levelID: 0,
    levelIndex: 0,
    dateTimeArray: null,
    lastPayTime: null,
    lastPayTimeText: '',
    createTime: null,
    createTimeText: '',
    // 显示加载更多 loading
    hothidden: true,
    loadinghidden: true,
    isAddBtnShow: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    /**
     * 获取系统信息
     */
    wx.getSystemInfo({

      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(2000, 2030);

    var nowTimeText = obj.dateTimeArray[0][obj.dateTime[0]] + '-' + obj.dateTimeArray[1][obj.dateTime[1]] + '-' + obj.dateTimeArray[2][obj.dateTime[2]] + ' ' + obj.dateTimeArray[3][obj.dateTime[3]] + ':' + obj.dateTimeArray[4][obj.dateTime[4]] + ':' +
      obj.dateTimeArray[5][obj.dateTime[5]];

    that.setData({
      lastPayTime: obj.dateTime,
      createTime: obj.dateTime,
      lastPayTimeText: nowTimeText,
      createTimeText: nowTimeText,
      dateTimeArray: obj.dateTimeArray,
    });

    that.doLoadData();
    that.loadOrgData();
  },
  onShow: function () {
    var that = this;
  },
  //加载数据
  doLoadData: function () {
    var that = this;

    var parameter = {};
    parameter['page'] = 1;

    /**
     * 显示 loading
     */
    that.setData({
      page: 1,
      loadinghidden: false,
      hothidden: false,
    });

    parameter['keyword'] = that.data.keyword;

    var url = apiUrl.UrlMemberList;
    if(that.data.navSelectIndex>0){
      url = apiUrl.UrlAdminSearch;
    }

    http.ApiGet(url, parameter, function (res) {
      wx.stopPullDownRefresh(); //停止下拉刷新
      wx.hideNavigationBarLoading(); //完成停止加载
      that.setData({
        loadinghidden: true
      })
      if (res.result.errorCode == 1) {
        var dataList = res.data;
        if (dataList.length > 0) {
          dataList = dataList.map(function (item) {
            let day = (365-((new Date().getTime()/1000)-item.last_pay_time)/(60*60*24)).toFixed();
            if(day>0){
                if(day<=30){
                  item.last_pay_time_text+='(距离下次缴费还有'+day+'天)';
                }
            }else{
              item.last_pay_time_text+='(已欠费)';
            }
            return item;
          })
        }

        that.setData({
          page: 1,
          hothidden: false,
          dataList: dataList
        });
      } else {
        wx.showModal({
          title: res.result.errorMessage
        });
      }
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.doLoadData();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;

    // 加载更多 loading
    that.setData({
      hothidden: true
    })

    var page = that.data.page + 1;
    // 获取当前现有数据进行保存
    var list = that.data.dataList;

    var parameter = {};
    parameter['page'] = page;
    parameter['keyword'] = that.data.keyword;

    var url = apiUrl.UrlMemberList;
    if(that.data.navSelectIndex>0){
      url = apiUrl.UrlAdminSearch;
    }

    http.ApiGet(url, parameter, function (res) {
      if (res.result.errorCode == 1) {
        var newData = res.data;
        if (newData.length > 0) {
          that.setData({
            page: page,
            hothidden: false,
            dataList: list.concat(newData.map(function (item) {
              let day = (365-((new Date().getTime()/1000)-item.last_pay_time)/(60*60*24)).toFixed();
              if(day>0){
                  if(day<=30){
                    item.last_pay_time_text+='(距离下次缴费还有'+day+'天)';
                  }
              }else{
                item.last_pay_time_text+='(已欠费)';
              }
              return item;
            }))
          });
        } else {
          that.setData({
            hothidden: false
          })
        }
      } else {
        wx.showModal({
          title: res.result.errorMessage
        });
      }
    });
  },
  //列表点击
  listCellTap: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var item = that.data.dataList[index];

    var ID = 0;
    if(item.admin_id){
      ID = item.admin_id;
    }else if(item.id){
      ID = item.id;
    }
    
    // console.log(ID);
    var link = "https://v.sogx.cn/wap/main/index/id/" + ID;
    wx.navigateTo({
      url: '../webview/index?url=' + link
    })
  },
  loadOrgData: function () {
    var that = this;

    var parameter = {};
    parameter['page'] = 1;
    //获取数据
    http.ApiGet(apiUrl.UrlOrgList, parameter, function (res) {
      wx.stopPullDownRefresh() //停止下拉刷新
      if (res.result.errorCode == 1) {
        var newData = res.data;
        if (newData.length > 0) {
          var orgName = [];
          var orgIndex = 0;
          var orgID = newData[0].id;


          newData.map(function (item, index) {
            orgName.push(item.name);
            if (orgID == item.id) {
              orgIndex = index;
            }
          });
          that.setData({
            orgArray: newData,
            orgNameArray: orgName,
            orgID: orgID,
            orgIndex: orgIndex
          });
          that.loadLevelData();
        }
      }
    });
  },
  loadLevelData: function () {
    var that = this;

    var parameter = {};
    parameter['page'] = 1;
    parameter['org_id'] = that.data.orgID;
    //获取数据
    http.ApiGet(apiUrl.UrlLevelList, parameter, function (res) {
      wx.stopPullDownRefresh() //停止下拉刷新
      if (res.result.errorCode == 1) {
        var newData = res.data;
        if (newData.length > 0) {
          var levelName = [];
          var levelIndex = 0;
          var levelID = newData[0].id;

          newData.map(function (item, index) {
            levelName.push(item.name);
            if (levelID == item.id) {
              levelIndex = index;
            }
          });
          that.setData({
            levelArray: newData,
            levelNameArray: levelName,
            levelID: levelID,
            levelIndex: levelIndex
          });
        }
      }
    });
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var orgArray = this.data.orgArray;
    this.setData({
      orgIndex: e.detail.value,
      orgID: orgArray[e.detail.value].id
    })
  },
  bindLevelPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var levelArray = this.data.levelArray;
    this.setData({
      levelIndex: e.detail.value,
      levelID: levelArray[e.detail.value].id
    })
  },
  editTap: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var item = that.data.dataList[index];
    console.log(item.id);
    that.setData({
      editID: item.id,
      orgID: item.org_id,
      adminID: item.admin_id,
      adminName: item.admin_nickname,
      inputViewShow: true,
    });

    var orgIndex = 0;
    var orgID = item.org_id;

    that.data.orgArray.map(function (item, index) {
      if (orgID == item.id) {
        orgIndex = index;
      }
    });

    that.setData({
      orgIndex: orgIndex
    });
    that.loadLevelData();
  },
  delTap: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var item = that.data.dataList[index];
    console.log(item.id);

    var formData = {};
    formData['id'] = item.id;

    wx.showModal({
      title: '确定删除？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定');
          http.ApiPost(apiUrl.UrlMemberDel, formData, function (res) {
            if (res.result.errorCode == 1) {
              that.doLoadData();
            } else {
              wx.showModal({
                title: res.result.errorMessage
              });
            }
          });
        }
      }
    });
  },
  addBtnTap: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var item = that.data.dataList[index];
    console.log(item.id);
    that.setData({
      editID: 0,
      adminID: item.id,
      adminName: item.nickname,
      orgId: 0,
      orgIndex: 0,
      inputViewShow: true,
    });
  },
  changeLastPayTime(e) {
    var lastPayTime = e.detail.value;
    var dateTimeArray = this.data.dateTimeArray;
    var lastPayTimeText = dateTimeArray[0][lastPayTime[0]] + '-' + dateTimeArray[1][lastPayTime[1]] + '-' + dateTimeArray[2][lastPayTime[2]] + ' ' + dateTimeArray[3][lastPayTime[3]] + ':' + dateTimeArray[4][lastPayTime[4]] + ':' +
      dateTimeArray[5][lastPayTime[5]];
    this.setData({
      lastPayTime: lastPayTime,
      lastPayTimeText: lastPayTimeText
    });
  },
  changeCreateTime(e) {
    var createTime = e.detail.value;
    var dateTimeArray = this.data.dateTimeArray;
    var createTimeText = dateTimeArray[0][createTime[0]] + '-' + dateTimeArray[1][createTime[1]] + '-' + dateTimeArray[2][createTime[2]] + ' ' + dateTimeArray[3][createTime[3]] + ':' + dateTimeArray[4][createTime[4]] + ':' +
      dateTimeArray[5][createTime[5]];
    this.setData({
      createTime: createTime,
      createTimeText: createTimeText
    });
  },
  doOK: function () {
    var that = this;
    var adminID = that.data.adminID;
    if (adminID==0) {
      wx.showModal({
        title: '不能为空'
      });
      return;
    }
    that.closeInput();
    that.doEditPost({
      'id': that.data.editID,
      'org_id': that.data.orgID,
      'admin_id': that.data.adminID,
      'level_id': that.data.levelID,
      'last_pay_time': util.dateStrChangeTimeTamp(that.data.lastPayTimeText),
      'create_time': util.dateStrChangeTimeTamp(that.data.createTimeText),
    });
  },
  closeInput: function () {
    this.setData({
      inputViewShow: false,
    });
  },
  navItemTap: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.id;
    that.setData({
      navSelectIndex: index,
      page: 1
    });

    that.doLoadData();
  },
  searchContentInput: function (e) {
    this.setData({
      keyword: e.detail.value
    })
  },
  searchSubmit: function () {
    var that = this;
    that.doLoadData();
  },
  doEditPost: function (postData) {
    var that = this;

    http.ApiPost(apiUrl.UrlMemberSubmit, postData, function (res) {
      if (res.result.errorCode == 1) {
        wx.hideToast()
        wx.showToast({
          title: '操作成功！',
          icon: 'success',
          duration: 3000
        });
        that.doLoadData();
        setTimeout(function () {
          wx.hideToast();
        }, 1000)
      } else {
        wx.showModal({
          title: res.result.errorMessage
        });
      }
    });
  },
  sendTap: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var item = that.data.dataList[index];
    wx.navigateTo({
      url: '../member/noticeSubmit?title=新建通知&adminID='+item.admin_id
    })
  }
})